package com.hang.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hang.common.BizErrorCodeEnum;
import com.hang.common.BizException;
import com.hang.config.RedisConfig;
import com.hang.model.Attendance;
import com.hang.service.AttendanceService;
import com.hang.mapper.AttendanceMapper;
import com.hang.vo.LeavesDTO;
import com.hang.vo.PunchVo;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

/**
 *
 */
@Service
public class AttendanceServiceImpl extends ServiceImpl<AttendanceMapper, Attendance>
    implements AttendanceService{

    @Autowired
    private RedisConfig redisConfig;

    /**
     * 学生打卡
     * @param studentId
     * @param taskId
     * @return
     */
    @Override
    public Boolean punchClock(String studentId, Long taskId) {
        /**
         * 1.先去redis中修改这个任务的学生状态
         * 2.如果没有读到这个任务，那么就去mysql中读，如果没有，则抛异常
         */
        RedisTemplate<String, Object> redisTemplate = redisConfig.getRedisTemplateByDb(1);

        Boolean hasKey = redisTemplate.opsForHash().hasKey(String.valueOf(taskId), studentId);
        QueryWrapper<Attendance> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("task_id",taskId);
        queryWrapper.eq("student_id",studentId);

        Attendance attendance = baseMapper.selectOne(queryWrapper);

        //先不同步到数据库，而是存在缓存中

        if(hasKey){
            //如果存在这个任务，这个学生，那么就进行打卡
            redisTemplate.opsForHash().put(String.valueOf(taskId),studentId,1);

            //修改数据库的状态
            if(!ObjectUtils.isEmpty(attendance)){
                attendance.setStatus(1);
                baseMapper.updateById(attendance);
            }

        }else {
            //修改数据库状态
            if(ObjectUtils.isEmpty(attendance)){
                return Boolean.FALSE;
            }

            attendance.setStatus(1);
            baseMapper.updateById(attendance);

            //缓存回数据库
            redisTemplate.opsForHash().put(String.valueOf(taskId),studentId,1);
        }

        return Boolean.TRUE;
    }

    /**
     * 记录打卡时间 => DB2
     * @param studentId
     * @param taskId
     */
    @Override
    public void recordPunchTime(String studentId, Long taskId) {
        RedisTemplate<String, Object> redisTemplate = redisConfig.getRedisTemplateByDb(2);

        String localDateTime = LocalDateTime.now().toString();
        redisTemplate.opsForHash().put(String.valueOf(taskId),studentId,localDateTime);
    }

    @Override
    public Map<String, Object> getPunchTime(Long taskId) {
        if(ObjectUtils.isEmpty(taskId)){
            throw new BizException(BizErrorCodeEnum.ID_IS_NULL);
        }

        RedisTemplate<String, Object> redisTemplate = redisConfig.getRedisTemplateByDb(2);

        Map<String, String> entries = redisTemplate.<String, String>opsForHash().entries(String.valueOf(taskId));
        List<PunchVo> punchVos = new LinkedList<>();

        for (Map.Entry<String, String> entry : entries.entrySet()) {
            if(StringUtils.isNotBlank(entry.getValue()) && StringUtils.isNotBlank(entry.getKey())){
                punchVos.add(new PunchVo(entry.getKey(),entry.getValue()));
            }
        }


        Map<String,Object> map = new HashMap<>();
        map.put("list",punchVos);

        return map;
    }
}




